# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from MsgProcess import MsgProcess, MsgType
from threading import Thread
import time,os
import package.SpeechSynthesis as SpeechSynthesis

class LightBlocking(MsgProcess):
    play =SpeechSynthesis.SpeechSynthesis(MsgProcess)	
    key = 0

    def say(self,text):
        self.send(MsgType=MsgType.Text, Receiver="Screen", Data=text)
        self.play.Text({"Data":text,'Sender':""})

    def Start_run(self):
        pin = 15
        while 1:
    
            time.sleep(0.5)
            #是否启动
            if self.key ==1:

                self.say("物体检测启动完成")
                GPIO.setmode(GPIO.BOARD)#设置引脚编号规则
                GPIO.setup(pin, GPIO.IN)#将引脚设置成输入模式
                #检测传感器是否已经接入
                if GPIO.input(pin)==0:
                    value = 0
                    while 1:
                        #检测传感器是否检测到
                        if GPIO.input(pin)==1:
                            value+=1
                            self.send(MsgType=MsgType.Text, Receiver='CurrencyLamp', Data=0.2)#亮的时间
                            self.say(str(value))

                        if self.key ==0:
                            self.say("物体检测已关闭")   
                            break

                        time.sleep(0.05)



    def Start(self,x):
        Thread( target=self.Start_run ).start()

    def Text(self, message):
        data = message["Data"]
        if not "关闭" in data:
            if self.key==1:
                self.say("进程已存在，请先关闭。") 
                return 0
            self.key=1

        if "关闭" in data:
            self.key=0
            

